package com.envper.security.utils;

import com.envper.mysql.domain.dto.TokenDto;
import com.envper.common.util.RedisUtils;
import com.envper.security.domain.LoginUser;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Component
@RequiredArgsConstructor
public class TokenUtils {
    private final RedisUtils redisUtils;
    private final HttpServletResponse response;
    private final HttpServletRequest request;

    // 令牌自定义标识
    @Value("${safety.token.header}")
    private String header;

    // 令牌前缀
    @Value("${safety.token.prefix}")
    private String prefix;

    public TokenDto createToken(LoginUser loginUser) {
        String token = UUID.randomUUID().toString();
        redisUtils.setCacheObject(token, loginUser, 7, TimeUnit.DAYS);
        response.addHeader(header, prefix + " " + token);
        return TokenDto.builder()
                .content(token)
                .prefix(prefix)
                .header(header)
                .build();
    }

    public String getToken() {
        return request.getHeader(header);
    }

    public LoginUser getLoginUser(HttpServletRequest request) {
        String token = request.getHeader(header);
        if (StringUtils.hasText(token)) {
            token = token.substring(prefix.length()).trim();
            Object object = redisUtils.getCacheObject(token, LoginUser.class);
            if (object instanceof LoginUser loginUser) {
                return loginUser;
            }
        }
        return null;
    }

    public boolean removeToken() {
        String token = getToken();
        if (StringUtils.hasText(token)) {
            String key = token.replace(prefix, "").trim();
            System.out.println("key = " + key);
            return redisUtils.deleteObject(key);
        }
        return false;
    }
}
